package com.zy.datareceiver.binsess.warning.service.impl;

import com.zy.datareceiver.binsess.decode.service.StorageTaskService;
import com.zy.datareceiver.binsess.warning.entity.WarningData;
import com.zy.datareceiver.binsess.warning.mapper.WarningDataMapper;
import com.zy.datareceiver.core.cast.ConCast;
import com.zy.datareceiver.core.common.SpringApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class SaveWarningDataDB extends Thread {

    private WarningDataMapper warningDataMapper = SpringApplicationContext.getBean(WarningDataMapper.class);

    private static final Logger log = LoggerFactory.getLogger(SaveWarningDataDB.class);

    @Override
    public void run() {
        while(true){
            try {
                long now = System.currentTimeMillis();
                List<WarningData> warningDataList = new ArrayList<>();
                WarningData warningData = StorageTaskService.warningQueue.take();
                warningDataList.add(warningData);
                if (warningDataList.size() > 10 || System.currentTimeMillis() - now > ConCast.DB.WARNING_DATA_TO_DB_OUT_OF_TIME){
                    warningDataMapper.batchInsert(warningDataList);
                    warningDataList.clear();
                }
            } catch (InterruptedException e) {
                log.error(" 预警数据入库出现异常，异常信息 {}",e);
            }
        }
    }
}
